// common/http.interceptor.js

import { getToken, Login } from "./utils";

import Vue from "vue";
let baseUrl = "";
if (process.env.NODE_ENV === "development") {
	// 开发环境
	baseUrl = "http://yxadmin.xyz:8080/api";
	Vue.prototype.$baseUrl = "http://yxadmin.xyz:8080";
	Vue.prototype.$baseImgUrl =
		"http://yxadmin.xyz:8080/api/UpLoad/UploadFile";
} else {
	// 生产环境
	baseUrl = "http://yxadmin.xyz:8080/api";
	Vue.prototype.$baseUrl = "http://yxadmin.xyz:8080";
	Vue.prototype.$baseImgUrl =
		"http://yxadmin.xyz:8080/api/UpLoad/UploadFile";
}
const install = (Vue, vm) => {
	// 此为自定义配置参数，具体参数见上方说明
	Vue.prototype.$u.http.setConfig((config) => {
		config.baseURL = baseUrl;
		// config.loadingText = "加载中……";
		// config.loadingTime = 800;
		config.header = {
			"content-type": "application/json"
		};
		config.originalData = true;
		config.custom = {
			loading: true,
		};
		return config;
	});

	// 请求拦截部分，如配置，每次请求前都会执行

	Vue.prototype.$u.http.interceptors.request.use((config) => {
		const token = getToken();
		// const token = '7EF0870EBF8B43A69C42CE9A8FB062541111=44a2aa83fedd91bc6ee8da20ccc8efd3'
		if (token) {
			config.header.Authorization = "Bearer " + token;
			// console.log(token, "token");
		} else {
			config.header.Authorization = "";
		}
		if (config.custom.loading) {
			uni.showLoading({
				title: "加载中",
			});
		}
		return config;
	});

	// 响应拦截，如配置，每次请求结束都会执行本方法
	uni.$u.http.interceptors.response.use(
		(res) => {
			// console.log(res, 'res')
			const loading = res.config?.custom?.loading;
			if (loading) {
				uni.hideLoading();
			}

			if (res.statusCode == 200) {

				if (!res.data.flag) {
					vm.$u.toast(res.data.err);
				} else {
					// uni.redirectTo({
					// 	url: "/pages/home/index.vue",
					// });

					return res.data;
				}
			} else {

				return Promise.reject(res.data);
			}
		},
		(response) => {
			// console.log(response);
			// 判断请求状态错误码统一处理
			let errMsg = "";
			switch (response.statusCode) {
				case 400:
					errMsg = "错误请求";
					break;
				case 401:
					// console.log("401 - 2");
					errMsg = "身份过期，重新登录";

					break;
				case 403:
					errMsg = "拒绝访问";
					break;
				case 404:
					errMsg = "请求错误,未找到该资源";
					break;
				case 405:
					errMsg = "请求方法未允许";
					break;
				case 408:
					errMsg = "请求超时";
					break;
				case 500:
					errMsg = "服务器端出错";
					break;
				case 501:
					errMsg = "网络未实现";
					break;
				case 502:
					errMsg = "网络错误";
					break;
				case 503:
					errMsg = "服务不可用";
					break;
				case 504:
					errMsg = "网络超时";
					break;
				case 505:
					errMsg = "http版本不支持该请求";
					break;
				default:
					errMsg = `连接错误`;
			}
			vm.$u.toast(errMsg);
			// return false;
			return Promise.reject(response);
		}
	);
};

export default {
	install
};